package org.algorithm.熊猫.数组.三月.第三周;

/**
 * @date 2022/03/17 10:08 PM
 * @description: 周五作业
 * <p>
 * <p>
 * url: https://leetcode-cn.com/problems/container-with-most-water/
 */
public class 盛最多水的容器 {

    public static void main(String[] args) {
        int[] nums = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        System.out.println(maxArea2(nums));
    }


    /**
     * 暴力双循环
     *
     * @param nums
     * @return
     */
    public static int maxArea(int[] nums) {
        int res = 0;
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int chang = j - i;
                int kuan = Math.min(nums[i], nums[j]);
                res = Math.max(res, chang * kuan);
            }
        }
        return res;
    }

    /**
     * 双指针
     * 如何移动双指针，该移动哪一个？
     * 题目为盛水最多的容器，即受限于最高度最低的一侧容器高度，（数组元素的值）
     *
     * @param nums
     * @return
     */
    public static int maxArea2(int[] nums) {
        int res = 0;
        int n = nums.length;
        int left = 0;
        int right = n - 1;
        int leftMax = 0;
        int rightMax = 0;
        while (left < right) {
            int leftInt = nums[left];
            int rightInt = nums[right];
            if (leftInt < rightInt) {
                if (leftInt > leftMax) {
                    res = Math.max(res, leftInt * (right - left));
                    leftMax = leftInt;
                }
                left++;
            } else {
                if (rightInt > rightMax) {
                    res = Math.max(res, rightInt * (right - left));
                    rightMax = rightInt;
                }
                right--;
            }
        }
        return res;
    }
}
